package androidx.test.espresso.base;

import android.app.Activity;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.test.espresso.NoActivityResumedException;
import androidx.test.espresso.NoMatchingRootException;
import androidx.test.espresso.Root;
import androidx.test.espresso.UiController;
import androidx.test.espresso.core.internal.deps.guava.base.Preconditions;
import androidx.test.espresso.core.internal.deps.guava.collect.ImmutableList;
import androidx.test.espresso.core.internal.deps.guava.collect.Lists;
import androidx.test.espresso.core.internal.deps.guava.collect.UnmodifiableIterator;
import androidx.test.espresso.matcher.RootMatchers;
import androidx.test.internal.util.LogUtil;
import androidx.test.runner.lifecycle.ActivityLifecycleMonitor;
import androidx.test.runner.lifecycle.Stage;
import com.sangfor.ssl.service.utils.IGeneral;
import com.tencent.smtt.sdk.TbsListener;
import com.tencent.smtt.sdk.TbsMediaPlayer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import javax.inject.Provider;
import org.hamcrest.Matcher;

/* loaded from: classes.dex */
public final class RootViewPicker implements Provider<View> {
    private static final ImmutableList<Integer> CREATED_WAIT_TIMES = ImmutableList.of((Integer) 10, (Integer) 50, (Integer) 150, Integer.valueOf((int) ItemTouchHelper.Callback.DEFAULT_SWIPE_ANIMATION_DURATION));
    private static final ImmutableList<Integer> RESUMED_WAIT_TIMES = ImmutableList.of((Integer) 10, (Integer) 50, (Integer) 100, Integer.valueOf((int) TbsListener.ErrorCode.INFO_CODE_MINIQB), (Integer) 2000, Integer.valueOf((int) IGeneral.TIMEQRY_SLEEP));
    private static final String TAG = "RootViewPicker";
    private final ActivityLifecycleMonitor activityLifecycleMonitor;
    private final AtomicReference<Boolean> needsActivity;
    private final RootResultFetcher rootResultFetcher;
    private final UiController uiController;

    public RootViewPicker(UiController uiController, RootResultFetcher rootResultFetcher, ActivityLifecycleMonitor activityLifecycleMonitor, AtomicReference<Boolean> needsActivity) {
        this.uiController = uiController;
        this.rootResultFetcher = rootResultFetcher;
        this.activityLifecycleMonitor = activityLifecycleMonitor;
        this.needsActivity = needsActivity;
    }

    @Override // javax.inject.Provider
    public View get() {
        Preconditions.checkState(Looper.getMainLooper().equals(Looper.myLooper()), "must be called on main thread.");
        if (this.needsActivity.get().booleanValue()) {
            waitForAtLeastOneActivityToBeResumed();
        }
        return pickRootView();
    }

    private Root waitForRootToBeReady(Root pickedRoot) {
        long currentTimeMillis = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(10L);
        RootReadyBackoff rootReadyBackoff = new RootReadyBackoff();
        while (System.currentTimeMillis() <= currentTimeMillis) {
            if (pickedRoot.isReady()) {
                return pickedRoot;
            }
            this.uiController.loopMainThreadForAtLeast(rootReadyBackoff.getNextBackoffInMillis());
        }
        throw new RuntimeException(String.format("Waited for the root of the view hierarchy to have window focus and not request layout for 10 seconds. If you specified a non default root matcher, it may be picking a root that never takes focus. Root:\n%s", pickedRoot));
    }

    private Root pickARoot() {
        long currentTimeMillis = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(60L);
        RootResults fetch = this.rootResultFetcher.fetch();
        NoActiveRootsBackoff noActiveRootsBackoff = new NoActiveRootsBackoff();
        NoMatchingRootBackoff noMatchingRootBackoff = new NoMatchingRootBackoff();
        while (System.currentTimeMillis() <= currentTimeMillis) {
            int i = AnonymousClass1.$SwitchMap$androidx$test$espresso$base$RootViewPicker$RootResults$State[fetch.getState().ordinal()];
            if (i == 1) {
                return fetch.getPickedRoot();
            }
            if (i == 2) {
                this.uiController.loopMainThreadForAtLeast(noActiveRootsBackoff.getNextBackoffInMillis());
            } else if (i == 3) {
                this.uiController.loopMainThreadForAtLeast(noMatchingRootBackoff.getNextBackoffInMillis());
            }
            fetch = this.rootResultFetcher.fetch();
        }
        if (RootResults.State.ROOTS_PICKED == fetch.getState()) {
            return fetch.getPickedRoot();
        }
        throw NoMatchingRootException.create(fetch.rootSelector, fetch.allRoots);
    }

    /* renamed from: androidx.test.espresso.base.RootViewPicker$1 */
    /* loaded from: classes.dex */
    public static /* synthetic */ class AnonymousClass1 {
        static final /* synthetic */ int[] $SwitchMap$androidx$test$espresso$base$RootViewPicker$RootResults$State;

        static {
            int[] iArr = new int[RootResults.State.values().length];
            $SwitchMap$androidx$test$espresso$base$RootViewPicker$RootResults$State = iArr;
            try {
                iArr[RootResults.State.ROOTS_PICKED.ordinal()] = 1;
            } catch (NoSuchFieldError unused) {
            }
            try {
                $SwitchMap$androidx$test$espresso$base$RootViewPicker$RootResults$State[RootResults.State.NO_ROOTS_PRESENT.ordinal()] = 2;
            } catch (NoSuchFieldError unused2) {
            }
            try {
                $SwitchMap$androidx$test$espresso$base$RootViewPicker$RootResults$State[RootResults.State.NO_ROOTS_PICKED.ordinal()] = 3;
            } catch (NoSuchFieldError unused3) {
            }
        }
    }

    private View pickRootView() {
        return waitForRootToBeReady(pickARoot()).getDecorView();
    }

    private void waitForAtLeastOneActivityToBeResumed() {
        Collection<Activity> activitiesInStage = this.activityLifecycleMonitor.getActivitiesInStage(Stage.RESUMED);
        if (activitiesInStage.isEmpty()) {
            this.uiController.loopMainThreadUntilIdle();
            activitiesInStage = this.activityLifecycleMonitor.getActivitiesInStage(Stage.RESUMED);
        }
        if (activitiesInStage.isEmpty()) {
            ArrayList newArrayList = Lists.newArrayList();
            UnmodifiableIterator<Integer> it = CREATED_WAIT_TIMES.iterator();
            while (it.hasNext()) {
                long intValue = it.next().intValue();
                Iterator it2 = EnumSet.range(Stage.PRE_ON_CREATE, Stage.RESTARTED).iterator();
                while (it2.hasNext()) {
                    newArrayList.addAll(this.activityLifecycleMonitor.getActivitiesInStage((Stage) it2.next()));
                }
                if (!newArrayList.isEmpty()) {
                    break;
                }
                String str = TAG;
                StringBuilder sb = new StringBuilder(72);
                sb.append("No activities found - waiting: ");
                sb.append(intValue);
                sb.append("ms for one to appear.");
                Log.w(str, sb.toString());
                this.uiController.loopMainThreadForAtLeast(intValue);
            }
            if (newArrayList.isEmpty()) {
                throw new RuntimeException("No activities found. Did you t to launch the activity by calling getActivity() or startActivitySync or similar?");
            }
            UnmodifiableIterator<Integer> it3 = RESUMED_WAIT_TIMES.iterator();
            while (it3.hasNext()) {
                long intValue2 = it3.next().intValue();
                String str2 = TAG;
                StringBuilder sb2 = new StringBuilder(82);
                sb2.append("No activity currently resumed - waiting: ");
                sb2.append(intValue2);
                sb2.append("ms for one to appear.");
                Log.w(str2, sb2.toString());
                this.uiController.loopMainThreadForAtLeast(intValue2);
                if (!this.activityLifecycleMonitor.getActivitiesInStage(Stage.RESUMED).isEmpty()) {
                    return;
                }
            }
            throw new NoActivityResumedException("No activities in stage RESUMED. Did you t to launch the activity. (test.getActivity() or similar)?");
        }
    }

    /* loaded from: classes.dex */
    public static class RootResults {
        private final List<Root> allRoots;
        private final List<Root> pickedRoots;
        private final Matcher<Root> rootSelector;

        /* loaded from: classes.dex */
        public enum State {
            NO_ROOTS_PRESENT,
            NO_ROOTS_PICKED,
            ROOTS_PICKED
        }

        /* synthetic */ RootResults(List list, List list2, Matcher matcher, AnonymousClass1 anonymousClass1) {
            this(list, list2, matcher);
        }

        private RootResults(List<Root> allRoots, List<Root> pickedRoots, Matcher<Root> rootSelector) {
            this.allRoots = allRoots;
            this.pickedRoots = pickedRoots;
            this.rootSelector = rootSelector;
        }

        private static boolean isTopmostRoot(Root topMostRoot, Root root) {
            return root.getWindowLayoutParams().get().type > topMostRoot.getWindowLayoutParams().get().type;
        }

        public State getState() {
            if (this.allRoots.isEmpty()) {
                return State.NO_ROOTS_PRESENT;
            }
            if (this.pickedRoots.isEmpty()) {
                return State.NO_ROOTS_PICKED;
            }
            if (this.pickedRoots.size() >= 1) {
                return State.ROOTS_PICKED;
            }
            return State.NO_ROOTS_PICKED;
        }

        private Root getRootFromMultipleRoots() {
            Root root = this.pickedRoots.get(0);
            if (this.pickedRoots.size() >= 1) {
                for (Root root2 : this.pickedRoots) {
                    if (RootMatchers.isDialog().matches(root2)) {
                        return root2;
                    }
                    if (isTopmostRoot(root, root2)) {
                        root = root2;
                    }
                }
            }
            return root;
        }

        public Root getPickedRoot() {
            if (this.pickedRoots.size() > 1) {
                LogUtil.logDebugWithProcess(RootViewPicker.TAG, "Multiple root windows detected: %s", this.pickedRoots);
                return getRootFromMultipleRoots();
            }
            return this.pickedRoots.get(0);
        }
    }

    /* loaded from: classes.dex */
    public static class RootResultFetcher {
        private final ActiveRootLister activeRootLister;
        private final Matcher<Root> selector;

        public RootResultFetcher(ActiveRootLister activeRootLister, AtomicReference<Matcher<Root>> rootMatcherRef) {
            this.activeRootLister = activeRootLister;
            this.selector = rootMatcherRef.get();
        }

        public RootResults fetch() {
            List<Root> listActiveRoots = this.activeRootLister.listActiveRoots();
            ArrayList newArrayList = Lists.newArrayList();
            for (Root root : listActiveRoots) {
                if (this.selector.matches(root)) {
                    newArrayList.add(root);
                }
            }
            return new RootResults(listActiveRoots, newArrayList, this.selector, null);
        }
    }

    /* loaded from: classes.dex */
    public static abstract class BackOff {
        private final List<Integer> backoffTimes;
        private int numberOfAttempts = 0;
        private final TimeUnit timeUnit;

        protected abstract long getNextBackoffInMillis();

        public BackOff(List<Integer> backoffTimes, TimeUnit timeUnit) {
            this.backoffTimes = backoffTimes;
            this.timeUnit = timeUnit;
        }

        protected final long getBackoffForAttempt() {
            if (this.numberOfAttempts >= this.backoffTimes.size()) {
                List<Integer> list = this.backoffTimes;
                return list.get(list.size() - 1).intValue();
            }
            int intValue = this.backoffTimes.get(this.numberOfAttempts).intValue();
            this.numberOfAttempts++;
            return this.timeUnit.toMillis(intValue);
        }
    }

    /* loaded from: classes.dex */
    public static final class NoActiveRootsBackoff extends BackOff {
        private static final ImmutableList<Integer> NO_ACTIVE_ROOTS_BACKOFF = ImmutableList.of(10, 10, 20, 30, 50, 80, 130, (int) Integer.valueOf((int) TbsListener.ErrorCode.ROM_NOT_ENOUGH), 340);

        public NoActiveRootsBackoff() {
            super(NO_ACTIVE_ROOTS_BACKOFF, TimeUnit.MILLISECONDS);
        }

        @Override // androidx.test.espresso.base.RootViewPicker.BackOff
        public long getNextBackoffInMillis() {
            long backoffForAttempt = getBackoffForAttempt();
            LogUtil.logDebugWithProcess(RootViewPicker.TAG, "No active roots available - waiting: %sms for one to appear.", Long.valueOf(backoffForAttempt));
            return backoffForAttempt;
        }
    }

    /* loaded from: classes.dex */
    public static final class NoMatchingRootBackoff extends BackOff {
        private static final ImmutableList<Integer> NO_MATCHING_ROOT_BACKOFF = ImmutableList.of(10, 20, 200, (int) Integer.valueOf((int) TbsListener.ErrorCode.INFO_CODE_BASE), 1000, 2000);

        public NoMatchingRootBackoff() {
            super(NO_MATCHING_ROOT_BACKOFF, TimeUnit.MILLISECONDS);
        }

        @Override // androidx.test.espresso.base.RootViewPicker.BackOff
        public long getNextBackoffInMillis() {
            long backoffForAttempt = getBackoffForAttempt();
            Log.d(RootViewPicker.TAG, String.format("No matching root available - waiting: %sms for one to appear.", Long.valueOf(backoffForAttempt)));
            return backoffForAttempt;
        }
    }

    /* loaded from: classes.dex */
    public static final class RootReadyBackoff extends BackOff {
        private static final ImmutableList<Integer> ROOT_READY_BACKOFF = ImmutableList.of(10, 25, 50, 100, 200, (int) Integer.valueOf((int) TbsListener.ErrorCode.INFO_CODE_BASE), (int) Integer.valueOf((int) TbsMediaPlayer.TbsMediaPlayerListener.MEDIA_INFO_BAD_INTERLEAVING), 1000);

        public RootReadyBackoff() {
            super(ROOT_READY_BACKOFF, TimeUnit.MILLISECONDS);
        }

        @Override // androidx.test.espresso.base.RootViewPicker.BackOff
        public long getNextBackoffInMillis() {
            long backoffForAttempt = getBackoffForAttempt();
            Log.d(RootViewPicker.TAG, String.format("Root not ready - waiting: %sms for one to appear.", Long.valueOf(backoffForAttempt)));
            return backoffForAttempt;
        }
    }
}
